package com.heima.wemedia.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WemediaLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WemediaLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WemediaLoginServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WemediaLoginService {
    /**
     * 自媒体端登录
     *
     * @param dto
     */
    @Override
    public ResponseResult login(WemediaLoginDto dto) {
        //参数校验
        if(dto == null || StringUtils.isEmpty(dto.getPassword()) || StringUtils.isEmpty(dto.getName()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        //根据用户名查询用户信息
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if(wmUser == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");

        //验证登录密码
        String passwordByDigest = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if(!passwordByDigest.equals(wmUser.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        //返回用户信息和token
        Map users = new HashMap();
        users.put("name",wmUser.getName());
        users.put("phone",wmUser.getPhone());

        Map map = new HashMap();
        map.put("user",users);
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
        return ResponseResult.okResult(map);
    }
}
